package siwi.map.android;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockListFragment;
import com.wmw.DataPool.CommonData;
import com.wmw.Utility.Common;
import com.wmw.Utility.MSG;
import com.wmw.Utility.RegularExpression;
import com.wmw.Utility.DBConstant.DatabaseHelper;

import kankan.wheel.widget.NumericWheelAdapter;
import kankan.wheel.widget.WheelView;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.KeyListener;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class StoreCenter extends SherlockFragment {
	View _v;
	// 1.选中某个EditText后,光标不是定位到头部,而是末尾.
	
	private DatabaseHelper _openDBHelper;
	
	EditText _restaurantName;
	InputBox _phoneNumber;
	InputBox _minimumSendingPrice;
	InputBox _sendingPrice;
	InputBox _address;

	LinearLayout _llBusinessHours;
	List<RelativeLayout> _timeList = new ArrayList<RelativeLayout>();
	OnClickListener _oclBusinessHours = new OnClickListener() {
		TextView _curView;
		Dialog _dialog;
		Button _btnAdd;
		Button _btnModify;
		Button _btnDelete;

		WheelView _hourFrom;
		WheelView _minsFrom;
		WheelView _hourTo;
		WheelView _minsTo;

		@Override
		public void onClick(View v) {
			_curView = (TextView) v;
			SetSelectedState(_curView);

			_dialog = new Dialog(getActivity(), R.style.MyDialog);
			_dialog.setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					ResetStates(_curView);
				}
			});

			_dialog.setContentView(R.layout.time_layout);

			Window window = _dialog.getWindow();
			window.setWindowAnimations(R.style.dialogWindowAnim);
			window.setGravity(Gravity.TOP);
			window.setBackgroundDrawableResource(R.color.LightCyan);
			_dialog.show();

			// 填充整个屏幕的宽度
			WindowManager windowManager = getActivity().getWindowManager();
			Display display = windowManager.getDefaultDisplay();
			WindowManager.LayoutParams lp = window.getAttributes();
			lp.width = (int) (display.getWidth()); // 设置宽度
			window.setAttributes(lp);

			_btnAdd = (Button) _dialog.findViewById(R.id.T_L_Add);
			_btnAdd.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					int[] t = new int[4];
					t[0] = _hourFrom.getCurrentItem();
					t[1] = _minsFrom.getCurrentItem();
					t[2] = _hourTo.getCurrentItem();
					t[3] = _minsTo.getCurrentItem();
					addBusinessHour(TimeParser.TimeConvertToString(t));
					ResetStates(_curView);
					_dialog.cancel();
				}
			});

			_btnModify = (Button) _dialog.findViewById(R.id.T_L_Modify);
			_btnModify.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					int[] t = new int[4];
					t[0] = _hourFrom.getCurrentItem();
					t[1] = _minsFrom.getCurrentItem();
					t[2] = _hourTo.getCurrentItem();
					t[3] = _minsTo.getCurrentItem();
					TextView tv = (TextView) _curView;
					modifyBusinessHour(tv, TimeParser.TimeConvertToString(t));
					ResetStates(_curView);
					_dialog.cancel();
				}
			});

			_btnDelete = (Button) _dialog.findViewById(R.id.T_L_Delete);
			_btnDelete.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					View parent = (View) _curView.getParent();
					int readyToRemove = _timeList.indexOf(parent);
					removeBusinessHour(parent, readyToRemove);
					ResetStates(_curView);
					_dialog.cancel();
				}
			});

			// Ensure the number of items is 1~3.
			_btnDelete.setVisibility(_timeList.size() <= 1 ? View.GONE
					: View.VISIBLE);
			_btnAdd.setVisibility(_timeList.size() >= 3 ? View.GONE
					: View.VISIBLE);

			_hourFrom = (WheelView) _dialog.findViewById(R.id.hourFrom);
			_hourFrom.setAdapter(new NumericWheelAdapter(0, 23));
			_hourFrom.setLabel("时");
			_hourFrom.setCyclic(true);

			_minsFrom = (WheelView) _dialog.findViewById(R.id.minsFrom);
			_minsFrom.setAdapter(new NumericWheelAdapter(0, 59, "%02d"));
			_minsFrom.setLabel("分");
			_minsFrom.setCyclic(true);

			_hourTo = (WheelView) _dialog.findViewById(R.id.hourTo);
			_hourTo.setAdapter(new NumericWheelAdapter(0, 23));
			_hourTo.setLabel("时");
			_hourTo.setCyclic(true);

			_minsTo = (WheelView) _dialog.findViewById(R.id.minsTo);
			_minsTo.setAdapter(new NumericWheelAdapter(0, 59, "%02d"));
			_minsTo.setLabel("分");
			_minsTo.setCyclic(true);

			// // set current time
			// Calendar c = Calendar.getInstance();
			// int curHours = c.get(Calendar.HOUR_OF_DAY);
			// int curMinutes = c.get(Calendar.MINUTE);
			//
			String time = _curView.getText().toString();
			int[] t = new int[4];
			TimeParser.Parse(t, time);
			_hourFrom.setCurrentItem(t[0]);
			_minsFrom.setCurrentItem(t[1]);
			_hourTo.setCurrentItem(t[2]);
			_minsTo.setCurrentItem(t[3]);
		}
	};

	LinearLayout _llPhoneNumber;
	List<RelativeLayout> _phoneNumberList = new ArrayList<RelativeLayout>();
	OnClickListener _oclPhoneNumber = new OnClickListener() {
		TextView _curSelectedView;
		InputBox _inputBox;
		Dialog _dialog;
		Button _btnAdd;
		Button _btnModify;
		Button _btnDelete;

		@Override
		public void onClick(View v) {
			_curSelectedView = (TextView) v;
			SetSelectedState(_curSelectedView);

			_dialog = new Dialog(getActivity(), R.style.MyDialog);
			_dialog.setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					ResetStates(_curSelectedView);
				}
			});

			_dialog.setContentView(R.layout.phone_number_layout);

			Window window = _dialog.getWindow();
			window.setWindowAnimations(R.style.dialogWindowAnim);
			window.setGravity(Gravity.TOP);
			window.setBackgroundDrawableResource(R.color.LightCyan);
			_dialog.show();

			// Minimum Sending Price.
			EditText et = (EditText) _dialog.findViewById(R.id.PNL_EditText);
			ImageView ivClearPhoneNumber = (ImageView) _dialog
					.findViewById(R.id.PNL_ClearEditText);
			_inputBox = new InputBox(getActivity(), et, ivClearPhoneNumber,
					null, et.getPaddingRight(), RegularExpression.PhoneNumber,
					null);
			_inputBox.setContent(_curSelectedView.getText().toString());

			// 填充整个屏幕的宽度
			WindowManager windowManager = getActivity().getWindowManager();
			Display display = windowManager.getDefaultDisplay();
			WindowManager.LayoutParams lp = window.getAttributes();
			lp.width = (int) (display.getWidth()); // 设置宽度
			window.setAttributes(lp);

			_btnAdd = (Button) _dialog.findViewById(R.id.PNL_Add);
			_btnAdd.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (_inputBox.isValide()) {
						addPhoneNumber(_inputBox.getContent());
						ResetStates(_curSelectedView);
						_dialog.cancel();
					} else {
						Toast.makeText(getActivity(), "添加失败",
								Toast.LENGTH_SHORT).show();
					}
				}
			});

			_btnModify = (Button) _dialog.findViewById(R.id.PNL_Modify);
			_btnModify.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (_inputBox.isValide()) {
						TextView tv = (TextView) _curSelectedView;
						modifyPhoneNumber(tv, _inputBox.getContent());

						ResetStates(_curSelectedView);
						_dialog.cancel();
					} else {
						Toast.makeText(getActivity(), "修改失败",
								Toast.LENGTH_SHORT).show();
					}
				}
			});

			_btnDelete = (Button) _dialog.findViewById(R.id.PNL_Delete);
			_btnDelete.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					View parent = (View) _curSelectedView.getParent();
					int readyToRemove = _phoneNumberList.indexOf(parent);
					removePhoneNumber(parent, readyToRemove);

					ResetStates(_curSelectedView);
					_dialog.cancel();
				}
			});

			// Ensure the number of items is 1~3.
			_btnDelete.setVisibility(_phoneNumberList.size() <= 1 ? View.GONE
					: View.VISIBLE);
			_btnAdd.setVisibility(_phoneNumberList.size() >= 3 ? View.GONE
					: View.VISIBLE);
		}
	};

	private void ResetStates(TextView v) {
		v.setBackgroundColor(getResources().getColor(R.color.Transparent));
	}

	private void SetSelectedState(TextView v) {
		// Set to selected color.
		v.setBackgroundColor(getResources().getColor(R.color.TextBackground));
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Bundle bundle = getArguments();
		_openDBHelper = bundle != null ? (DatabaseHelper) bundle
				.getSerializable(MSG.DataBase) : null;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.store_center, container, false);
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initViews();
		initData();
	}

	@Override
	public void onStart() {
		super.onStart();
	}

	@Override
	public void onPause() {
		super.onPause();
	}


	static StoreCenter newInstance(DatabaseHelper dbHelper) {
		StoreCenter f = new StoreCenter();
		
		Bundle args = new Bundle();
		args.putSerializable(MSG.DataBase, dbHelper);
		f.setArguments(args);

		return f;
	}

	private void initViews() {
		// Store name.
		Activity activity = getActivity();
		_restaurantName = (EditText) activity
				.findViewById(R.id.SC_Content_StoreName);

		// Phone number.
		_llPhoneNumber = (LinearLayout) getActivity().findViewById(
				R.id.PC_PhoneNumberLinearLayout);
		int cnt = _llPhoneNumber.getChildCount();
		for (int i = 0; i < cnt; ++i) {
			RelativeLayout rl = (RelativeLayout) _llPhoneNumber.getChildAt(i);
			_phoneNumberList.add(rl);
		}

		// Minimum Sending Price.
		final EditText etMinimumSendingPrice = (EditText) getActivity().findViewById(
				R.id.P_C_Content_MinimumSendingPrice);
		ImageView ivClearMinimumSendingPrice = (ImageView) getActivity()
				.findViewById(R.id.P_C_Content_ClearMinimumSendingPrice);
		_minimumSendingPrice = new InputBox(activity, etMinimumSendingPrice,
				ivClearMinimumSendingPrice, null,
				etMinimumSendingPrice.getPaddingRight(),
				RegularExpression.MinimumSendingPrice, new InputBox.ShakeBox() {
					@Override
					public void Action(EditText et, String regularExpression,
							Context context, View v, boolean hasFocus) {
						super.Action(et, regularExpression, context, v,
								hasFocus);
					}

					@Override
					public void OnFocusChange(boolean valide, boolean hasFocus){
						super.OnFocusChange(valide, hasFocus);
						Log.d(Common.GetLineInfo(), "Focus -" + hasFocus);
						if (hasFocus)
							etMinimumSendingPrice.setBackgroundColor(getActivity().getResources().getColor(R.color.TextBackground));
						else {
							ExApplication app = (ExApplication)getActivity().getApplication();
							CommonData data = app._Data;
							if (valide){
								etMinimumSendingPrice.setBackgroundColor(getActivity().getResources().getColor(R.color.Transparent));
								// TODO
								Common.toastInfo(getActivity(), "通知修改最低起送价");
								
								data.set_minimumSendingPrice(Float.parseFloat(_minimumSendingPrice.getContent()));
							}
							else{
								Toast.makeText(getActivity(), "修改最低起送价失败", Toast.LENGTH_SHORT).show();
								_minimumSendingPrice.setContent(data.get_minimumSendingPrice() + "");
							}
						}
					}
				});

		// Sending Price.
		final EditText etSendingPrice = (EditText) getActivity().findViewById(
				R.id.P_C_Content_SendingPrice);
		ImageView ivClearSendingPrice = (ImageView) getActivity().findViewById(
				R.id.P_C_Content_ClearSendingPrice);
		_sendingPrice = new InputBox(getActivity(), etSendingPrice,
				ivClearSendingPrice, null, etSendingPrice.getPaddingRight(),
				RegularExpression.Fare, new InputBox.ShakeBox() {
					@Override
					public void Action(EditText et, String regularExpression,
							Context context, View v, boolean hasFocus) {
						super.Action(et, regularExpression, context, v,
								hasFocus);
					}

					@Override
					public void OnFocusChange(boolean valide, boolean hasFocus){
						super.OnFocusChange(valide, hasFocus);
						Log.d(Common.GetLineInfo(), "Focus -" + hasFocus);
						if (hasFocus)
							etSendingPrice.setBackgroundColor(getActivity().getResources().getColor(R.color.TextBackground));
						else  {
							ExApplication app = (ExApplication)getActivity().getApplication();
							CommonData data = app._Data;
							if (valide){
								etSendingPrice.setBackgroundColor(getActivity().getResources().getColor(R.color.Transparent));
								// TODO
								Common.toastInfo(getActivity(), "通知修改运费");
								
								data.set_sendingPrice(Float.parseFloat(_sendingPrice.getContent()));
							}
							else{
								Toast.makeText(getActivity(), "修改运费失败", Toast.LENGTH_SHORT).show();
								_sendingPrice.setContent(data.get_sendingPrice() + "");
							}
						}
					}
				});

		// Business Hours
		_llBusinessHours = (LinearLayout) getActivity().findViewById(
				R.id.PC_BusinessHourLinearLayout);
		int bhCnt = _llBusinessHours.getChildCount();
		for (int i = 0; i < bhCnt; ++i) {
			RelativeLayout rl = (RelativeLayout) _llBusinessHours.getChildAt(i);
			_timeList.add(rl);
		}
	}

	private void initData() {
		ExApplication app = (ExApplication) getActivity().getApplication();
		CommonData appData = app._Data;

		// Store name.
		_restaurantName.setText(appData.get_storeName());

		// Address.
		EditText etAddress1 = (EditText) getActivity().findViewById(
				R.id.P_C_Content_Address);
		TextView tvAddress2 = (TextView) getActivity().findViewById(
				R.id.P_C_Content_Address2);
		etAddress1.setText(appData.get_Address()[0]);
		tvAddress2.setText(appData.get_Address()[1]);

		// Minimum Sending Price.
		_minimumSendingPrice.setContent("" + appData.get_minimumSendingPrice());

		// Sending Price.
		_sendingPrice.setContent("" + appData.get_sendingPrice());

		// Phone number.
		EditText tvPhoneNumber = (EditText) getActivity().findViewById(
				R.id.P_C_Content_PhoneNumber);
		tvPhoneNumber.setOnClickListener(_oclPhoneNumber);
		tvPhoneNumber.setText(appData.get_phoneNumber()[0]);
		int cnt = appData.get_phoneNumber().length;
		for (int i = 1; i < cnt; ++i)
			addPhoneNumber(appData.get_phoneNumber()[i]);

		// Business Hour.
		EditText tvBusinessHours = (EditText) getActivity().findViewById(
				R.id.P_C_Content_BusinessHours_0);
		tvBusinessHours.setOnClickListener(_oclBusinessHours);
		tvBusinessHours.setText(appData.get_businessHours()[0]);
		cnt = appData.get_businessHours().length;
		for (int i = 1; i < cnt; ++i)
			addBusinessHour(appData.get_businessHours()[i]);

		// Brief Introduction
		EditText tvBriefIntroduction = (EditText) getActivity().findViewById(
				R.id.P_C_Content_BriefIntroduction);
		tvBriefIntroduction.setText(appData.get_briefIntroduction());
		tvBriefIntroduction.setOnClickListener(new OnClickListener() {
			TextView _curView;

			@Override
			public void onClick(View v) {
				_curView = (TextView) v;
				SetSelectedState(_curView);
				MyDialog dialog = new MyDialog();
				dialog.CreateADialog(getActivity(), _curView, 50,
						new MyDialog.Sure() {
							@Override
							public void onClickSure(String str) {
								_curView.setText(str);
								_curView.setBackgroundColor(getActivity()
										.getResources().getColor(
												R.color.Transparent));
							}
						});
			}
		});
	}

	private void addPhoneNumber(String phoneNumber) {
		// TODO
		Common.toastInfo(getActivity(), "通知添加电话号码");

		LayoutInflater inflater = LayoutInflater.from(getActivity());
		RelativeLayout layout = (RelativeLayout) inflater.inflate(
				R.layout.phone_number_view, null).findViewById(
				R.id.PNV_RelativeLayout);
		TextView tv = (TextView) layout.getChildAt(0);
		tv.setText(phoneNumber);
		tv.setOnClickListener(_oclPhoneNumber);
		LinearLayout lin = (LinearLayout) getActivity().findViewById(
				R.id.PC_PhoneNumberLinearLayout);
		lin.addView(layout);
		_phoneNumberList.add(layout);
	}

	private void modifyPhoneNumber(TextView tv, String phoneNumber) {
		// TODO
		Common.toastInfo(getActivity(), "通知修改电话号码");

		tv.setText(phoneNumber);
	}

	private void removePhoneNumber(View parent, int removeIdx) {
		// TODO
		Common.toastInfo(getActivity(), "通知删除电话号码");

		// First time, don't delete, just delete the last item, and
		// move up others.
		if (_phoneNumberList.contains(parent) && removeIdx == 0) {
			int lastOne = _phoneNumberList.size() - 1;
			TextView tvCopyTo = (TextView) _phoneNumberList.get(0)
					.getChildAt(1);
			for (int i = 0; i < lastOne; ++i) {
				RelativeLayout rlCopyFrom = _phoneNumberList.get(i + 1);
				TextView tvCopyFrom = (TextView) rlCopyFrom.getChildAt(0);
				String CopyFrom = tvCopyFrom.getText().toString();

				tvCopyTo.setText(CopyFrom);
				tvCopyTo = tvCopyFrom;
			}

			removeIdx = lastOne;
		}

		_llBusinessHours.removeView(_phoneNumberList.get(removeIdx));
		_phoneNumberList.remove(removeIdx);
	}

	private void addBusinessHour(String businessHour) {
		// TODO
		Common.toastInfo(getActivity(), "通知添加营业时间");

		LayoutInflater inflater = LayoutInflater.from(getActivity());
		RelativeLayout layout = (RelativeLayout) inflater.inflate(
				R.layout.time_view, null).findViewById(R.id.T_V_RelativeLayout);
		TextView tv = (TextView) layout.getChildAt(0);
		tv.setOnClickListener(_oclBusinessHours);
		tv.setText(businessHour);

		LinearLayout lin = (LinearLayout) getActivity().findViewById(
				R.id.PC_BusinessHourLinearLayout);
		lin.addView(layout);
		_timeList.add(layout);

	}

	private void modifyBusinessHour(TextView tv, String businessHour) {
		// TODO
		Common.toastInfo(getActivity(), "通知修改营业时间");

		tv.setText(businessHour);
	}

	private void removeBusinessHour(View parent, int removeIdx) {
		// TODO
		Common.toastInfo(getActivity(), "通知删除营业时间");

		// First time, don't delete, just delete the last item, and
		// move up others.
		if (_timeList.contains(parent) && removeIdx == 0) {
			int lastOne = _timeList.size() - 1;
			TextView tvCopyTo = (TextView) _timeList.get(0).getChildAt(1);
			for (int i = 0; i < lastOne; ++i) {
				RelativeLayout rlCopyFrom = _timeList.get(i + 1);
				TextView tvCopyFrom = (TextView) rlCopyFrom.getChildAt(0);
				String CopyFrom = tvCopyFrom.getText().toString();

				tvCopyTo.setText(CopyFrom);
				tvCopyTo = tvCopyFrom;
			}

			removeIdx = lastOne;
		}

		_llBusinessHours.removeView(_timeList.get(removeIdx));
		_timeList.remove(removeIdx);
	}

}
